/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Hashtable;

import com.aphrodite.util.StringUtil;

/**
 * Serialization utility for collections
 * 
 * @author kentelt
 * 
 */
public final class Serializer {

	/**
	 * Deserialize a hashtable
	 * 
	 * @param data
	 * @param delimiter
	 * @return
	 */
	public static Hashtable deSerializeHashtable(byte[] data, char delimiter) {
		Hashtable table = null;
		ByteArrayInputStream bins = new ByteArrayInputStream(data);
		DataInputStream dins = new DataInputStream(bins);
		try {
			int size = dins.readInt();
			table = new Hashtable(size);
			String value = null;
			for (int i = 0; i < size; i++) {
				value = dins.readUTF();
				String[] dat = StringUtil.split(value, delimiter, true);
				table.put(dat[0], dat[1]);
			}
		} catch (java.io.IOException e) {
			e.printStackTrace();
		}
		return table;
	}

	/**
	 * Serialize a hashtable.Both key and value part need to be of type
	 * java.lang.String
	 * 
	 * @param properties
	 * @param delimiter
	 *            usually a character that has a high probability of not
	 *            occuring in the key value pairs of the hashtable
	 * @return
	 */
	public static byte[] serializeHashtable(Hashtable properties, char delimiter) {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(bout);
		java.util.Enumeration keys = properties.keys();
		try {
			out.writeInt(properties.size());
			while (keys.hasMoreElements()) {
				String k = (String) keys.nextElement();
				String v = (String) properties.get(k);
				out.writeUTF(k + delimiter + v + '\n');
			}
		} catch (java.io.IOException e) {
			e.printStackTrace();
		}
		return bout.toByteArray();
	}
}
